<script setup lang="ts">
import {NButton, NCard, NModal, NSpace} from "naive-ui";
import {ref, watch} from "vue";
import {SelectBaseOption} from "naive-ui/es/select/src/interface";

interface Props {
  type: string;
  da: any;
}

defineOptions({
  name: 'DataInput'
});

const props = defineProps<Props>();
const emit = defineEmits(['cancel', 'confirm']);
const showModal = defineModel<boolean>('showModal', {
  default: false
});
const options = ref<SelectBaseOption[]>([]);
const da = ref({});
const data_v = ref('');
const data_m = ref('');

function onUpdate(value: any, option: any) {
  data_v.value = option.value;
  data_m.value = option.label;
  console.log(value, option);
}

function confirm() {
  emit('confirm', {
    r: props.da.r,
    c: props.da.c,
    v: data_v.value,
    m: data_m.value
  });
  showModal.value = false;
}

function cancel() {
  showModal.value = false;
}

function initData() {
  let t = props.type;
  if (t == '1') {
    let arr = props.da.d.d;
    let showCol = props.da.d.s;
    let valCol = props.da.d.v;
    for (let i = 0; i < arr.length; i++) {
      let row = arr[i];
      options.value.push({
        label: row[showCol],
        value: row[valCol]
      })
    }
    console.log(props.da);
    data_v.value = props.da.v;
    data_m.value = props.da.m;
  }

}

watch(showModal, () => {
  if (showModal.value) {
    da.value = props.da;
    initData()
  } else {
    data_m.value = '';
    data_v.value = '';
    options.value = [];
  }
});
</script>

<template>
  <n-space vertical style="padding-bottom: 0">
    <n-modal
      v-model:show="showModal"
    >
      <n-card
        style="width: 400px"
        title="选择值"
        size="huge"
        :bordered="false"
        role="dialog"
        aria-modal="true"
        header-style="padding: 1rem;"
        footer-style="padding: 1rem;text-align: right"
        content-style="padding: 0 1rem;"
      >
        <template #default>
          <n-select @update-value="onUpdate" :options="options" placeholder="请选择"/>
        </template>
        <template #footer>
          <n-button size="small" @click="cancel">取消</n-button>
          <n-button size="small" type="primary" @click="confirm" style="margin-left: 1rem">确定</n-button>
        </template>
      </n-card>
    </n-modal>
  </n-space>
</template>

<style scoped>

</style>
